<?php
/**
 * 编排监考员页面
 * 功能：管理监考员分配和排班
 * 权限：仅考试项目管理员可访问
 */

session_start();

// 检查用户是否已登录
if (!isset($_SESSION['user_id']) || !isset($_SESSION['username'])) {
    header('Location: index.php');
    exit();
}

$current_user_id = $_SESSION['user_id'] ?? '';
$GLOBALS['current_user_id'] = $current_user_id;

// 数据库连接
require_once 'database.php';

// 包含统一导航栏
if (file_exists('common/navigation.php')) {
    require_once 'common/navigation.php';
}

// 权限验证函数
if (!function_exists('getUserRoles')) {
    function getUserRoles($user_id, $conn) {
        $roles = [];
        try {
            $sql = "SELECT role FROM user_roles WHERE user_id = ?";
            $stmt = $conn->prepare($sql);

            if ($stmt) {
                $stmt->bind_param("s", $user_id);
                $stmt->execute();
                $result = $stmt->get_result();

                while ($row = $result->fetch_assoc()) {
                    $roles[] = $row['role'];
                }
                $stmt->close();
            }
        } catch (Exception $e) {
            error_log("获取用户角色失败: " . $e->getMessage());
        }

        return $roles;
    }
}

// 权限验证
$user_roles = getUserRoles($current_user_id, $conn);
if (!in_array('考试项目管理员', $user_roles)) {
    $_SESSION['error_message'] = "访问被拒绝：您需要考试项目管理员权限才能访问此页面";
    header('Location: access_denied.php');
    exit();
}

// 获取考试ID
$exam_id = intval($_GET['exam_id'] ?? 0);
if ($exam_id <= 0) {
    $_SESSION['error_message'] = "无效的考试项目ID";
    header('Location: exam_projects.php');
    exit();
}

$exam = null;
$error_message = '';
$success_message = '';

// 获取考试信息
try {
    $sql = "SELECT * FROM exams WHERE id = ? AND status = 'active'";
    $stmt = $conn->prepare($sql);

    if (!$stmt) {
        throw new Exception("数据库查询准备失败");
    }

    $stmt->bind_param("i", $exam_id);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows === 0) {
        $_SESSION['error_message'] = "考试项目不存在或已被删除";
        header('Location: exam_projects.php');
        exit();
    }

    $exam = $result->fetch_assoc();
    $stmt->close();

} catch (Exception $e) {
    $_SESSION['error_message'] = "获取考试信息失败: " . $e->getMessage();
    header('Location: exam_projects.php');
    exit();
}

$page_title = '编排监考员 - 考务管理系统';
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($page_title); ?></title>

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">

    <style>
        .main-content {
            margin-top: 20px;
            padding-bottom: 40px;
        }

        .page-header {
            background: linear-gradient(135deg, #ffc107 0%, #fd7e14 100%);
            color: white;
            padding: 30px;
            border-radius: 10px;
            margin-bottom: 20px;
            text-align: center;
        }

        .info-card {
            background: white;
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            padding: 20px;
            margin-bottom: 20px;
        }

        .feature-card {
            background: white;
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            padding: 30px;
            margin-bottom: 20px;
            text-align: center;
            transition: all 0.3s ease;
        }

        .feature-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 15px rgba(0,0,0,0.15);
        }

        .feature-icon {
            font-size: 3rem;
            margin-bottom: 20px;
            color: #ffc107;
        }

        .btn-back {
            margin-bottom: 20px;
        }

        .assignment-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
            margin-top: 20px;
        }

        .room-card {
            border: 1px solid #dee2e6;
            border-radius: 10px;
            padding: 20px;
            background: #f8f9fa;
        }

        .room-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }

        .invigilator-slot {
            border: 2px dashed #dee2e6;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 10px;
            text-align: center;
            color: #6c757d;
        }

        .invigilator-assigned {
            border-color: #28a745;
            background: #d4edda;
            color: #155724;
        }
    </style>
</head>
<body>
<!-- 统一导航栏 -->
<?php
if (file_exists('common/navigation.php')) {
    include_once 'common/navigation.php';
} else {
    echo '<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
                <div class="container">
                    <a class="navbar-brand" href="user_home.php">考务管理系统</a>
                    <div class="navbar-nav ms-auto">
                        <span class="navbar-text me-3">用户: ' . htmlspecialchars($current_user_id) . '</span>
                        <a class="nav-link" href="logout.php">退出登录</a>
                    </div>
                </div>
              </nav>';
}
?>

<!-- 主要内容 -->
<div class="container main-content">
    <!-- 返回按钮 -->
    <div class="btn-back">
        <a href="exam_projects.php" class="btn btn-secondary">
            <i class="fas fa-arrow-left"></i> 返回项目列表
        </a>
    </div>

    <!-- 页面标题 -->
    <div class="page-header">
        <h1 class="mb-2">
            <i class="fas fa-clipboard-check"></i> 编排监考员
        </h1>
        <p class="mb-0">项目：<?php echo htmlspecialchars($exam['exam_name']); ?></p>
    </div>

    <!-- 考试信息 -->
    <div class="info-card">
        <h5><i class="fas fa-info-circle"></i> 考试信息</h5>
        <div class="row">
            <div class="col-md-3">
                <strong>考试日期：</strong><br>
                <?php echo date('Y-m-d', strtotime($exam['exam_date'])); ?>
            </div>
            <div class="col-md-3">
                <strong>科目数量：</strong><br>
                <?php echo $exam['subject_count']; ?> 门
            </div>
            <div class="col-md-3">
                <strong>每科监考员：</strong><br>
                <?php echo $exam['invigilators_per_subject']; ?> 人
            </div>
            <div class="col-md-3">
                <strong>当前进度：</strong><br>
                <span class="badge bg-warning">阶段 <?php echo $exam['progress']; ?></span>
            </div>
        </div>
    </div>

    <!-- 功能模块 -->
    <div class="row">
        <div class="col-md-4">
            <div class="feature-card">
                <div class="feature-icon">
                    <i class="fas fa-user-tie"></i>
                </div>
                <h5>监考员管理</h5>
                <p class="text-muted">管理监考员信息</p>
                <button class="btn btn-warning" onclick="manageInvigilators()">
                    <i class="fas fa-users"></i> 管理监考员
                </button>
            </div>
        </div>

        <div class="col-md-4">
            <div class="feature-card">
                <div class="feature-icon">
                    <i class="fas fa-random"></i>
                </div>
                <h5>自动分配</h5>
                <p class="text-muted">自动分配监考员到考场</p>
                <button class="btn btn-success" onclick="autoAssign()">
                    <i class="fas fa-magic"></i> 自动分配
                </button>
            </div>
        </div>

        <div class="col-md-4">
            <div class="feature-card">
                <div class="feature-icon">
                    <i class="fas fa-calendar-alt"></i>
                </div>
                <h5>排班表</h5>
                <p class="text-muted">生成监考排班表</p>
                <button class="btn btn-info" onclick="generateSchedule()">
                    <i class="fas fa-table"></i> 生成排班表
                </button>
            </div>
        </div>
    </div>

    <!-- 监考员分配情况 -->
    <div class="info-card">
        <h5><i class="fas fa-clipboard-list"></i> 监考员分配情况</h5>

        <!-- 统计信息 -->
        <div class="row text-center mb-4">
            <div class="col-md-3">
                <h4 class="text-primary">0</h4>
                <p class="text-muted">可用监考员</p>
            </div>
            <div class="col-md-3">
                <h4 class="text-success">0</h4>
                <p class="text-muted">已分配</p>
            </div>
            <div class="col-md-3">
                <h4 class="text-warning">
                    <?php echo $exam['subject_count'] * $exam['invigilators_per_subject']; ?>
                </h4>
                <p class="text-muted">需要总数</p>
            </div>
            <div class="col-md-3">
                <h4 class="text-danger">
                    <?php echo $exam['subject_count'] * $exam['invigilators_per_subject']; ?>
                </h4>
                <p class="text-muted">未分配</p>
            </div>
        </div>

        <!-- 考场分配网格 -->
        <div class="assignment-grid">
            <?php for ($i = 1; $i <= $exam['subject_count']; $i++): ?>
                <div class="room-card">
                    <div class="room-header">
                        <h6><i class="fas fa-door-open"></i> 科目 <?php echo $i; ?></h6>
                        <span class="badge bg-secondary">0/<?php echo $exam['invigilators_per_subject']; ?></span>
                    </div>

                    <?php for ($j = 1; $j <= $exam['invigilators_per_subject']; $j++): ?>
                        <div class="invigilator-slot">
                            <i class="fas fa-user-plus"></i>
                            <div>监考员 <?php echo $j; ?></div>
                            <small class="text-muted">点击分配</small>
                        </div>
                    <?php endfor; ?>
                </div>
            <?php endfor; ?>
        </div>
    </div>
</div>

<!-- Bootstrap JS -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<!-- SweetAlert2 -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
    function manageInvigilators() {
        Swal.fire({
            title: '监考员管理',
            text: '监考员管理功能正在开发中...',
            icon: 'info',
            confirmButtonText: '确定'
        });
    }

    function autoAssign() {
        Swal.fire({
            title: '自动分配监考员',
            text: '自动分配功能正在开发中...',
            icon: 'info',
            confirmButtonText: '确定'
        });
    }

    function generateSchedule() {
        Swal.fire({
            title: '生成排班表',
            text: '排班表生成功能正在开发中...',
            icon: 'info',
            confirmButtonText: '确定'
        });
    }

    // 监考员分配点击事件
    document.querySelectorAll('.invigilator-slot').forEach(slot => {
        slot.addEventListener('click', function() {
            if (!this.classList.contains('invigilator-assigned')) {
                Swal.fire({
                    title: '分配监考员',
                    text: '监考员分配功能正在开发中...',
                    icon: 'info',
                    confirmButtonText: '确定'
                });
            }
        });
    });
</script>

<?php
// 关闭数据库连接
if (isset($conn) && $conn instanceof mysqli) {
    $conn->close();
}
?>
</body>
</html>